import {useCallback, useEffect, useLayoutEffect, useRef, useState} from 'react';
import {Icon, Text, TextInput, useAppTheme} from 'tsun-smart-ui';
import {useTranslation} from 'react-i18next';
import {
  Pressable,
  StyleSheet,
  View,
  TextInput as RNTextInput,
} from 'react-native';
import {stationApi} from '@/services/api/stationApi';
import {StationInstallerModel} from '@/services/api/stationApi';
import {FlashList} from '@shopify/flash-list';
function escapeRegExp(input: string): string {
  return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

const InstallerPicker = ({
  navigation,
  route: {
    params: {setValue},
  },
}: ReactNavigation.RootStackScreenProps<'InstallerPicker'>) => {
  const theme = useAppTheme();
  const [search, setSearch] = useState('');
  const searchRef = useRef<RNTextInput>(null);
  const [installers, setInstallers] = useState<StationInstallerModel[]>([]);
  const totalList = useRef<StationInstallerModel[]>([]);
  const [open, setOpen] = useState(false);
  const [selected, setSelected] = useState<
    StationInstallerModel['code'] | null
  >(null);
  const {t} = useTranslation();
  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <Text
          style={{
            color: selected
              ? theme.colors?.brand?.primary
              : theme.colors?.brand?.primaryDisabled,
          }}
          onPress={() => {
            navigation.goBack();
            setValue('parentCode', selected);
            setValue(
              'installer',
              installers.find(item => item.code === selected)?.name,
            );
          }}>
          {t('common.confirmButtonText')}
        </Text>
      ),
    });
  }, [selected]);
  useEffect(() => {
    stationApi.getStationInstallers().then(({data}) => {
      totalList.current = data;
    });
  }, []);
  const renderItem = useCallback(
    ({item, index}: {item: StationInstallerModel; index: number}) => {
      return (
        <Pressable
          className="   px-5"
          style={{
            backgroundColor: theme.colors?.neutral?.white,
            borderTopEndRadius: index === 0 ? 8 : 0,
            borderTopStartRadius: index === 0 ? 8 : 0,
            borderBottomEndRadius: index === installers.length - 1 ? 8 : 0,
            borderBottomStartRadius: index === installers.length - 1 ? 8 : 0,
          }}
          onPress={() => {
            setSearch(item.name);
            setSelected(item.code);
            searchRef.current?.blur();
            setOpen(false);
          }}>
          <View
            className="py-3 flex-row items-center justify-between"
            style={{
              borderBottomWidth:
                index === installers.length - 1 ? 0 : StyleSheet.hairlineWidth,
              borderBottomColor: theme.colors?.border?.primary,
              flex: 1,
            }}>
            {search ? (
              <Text>
                {item.name
                  .split(new RegExp(`(${escapeRegExp(search)})`, 'i'))
                  .map((part, index) =>
                    part.toLowerCase() === search.toLowerCase() ? (
                      <Text
                        key={index}
                        style={{color: theme.colors?.brand?.primary}}>
                        {part}
                      </Text>
                    ) : (
                      <Text key={index}>{part}</Text>
                    ),
                  )}
              </Text>
            ) : (
              <Text>{item.name}</Text>
            )}
          </View>
        </Pressable>
      );
    },
    [selected, installers],
  );
  return (
    <View className="px-4 flex-1">
      <TextInput
        className="mt-3"
        value={search}
        ref={searchRef}
        placeholder={t('common.search')}
        onFocus={() => {
          setOpen(true);
        }}
        onBlur={() => {
          if (search) {
            setInstallers(
              totalList.current.filter(item =>
                item.name.toLowerCase().includes(search.toLowerCase()),
              ),
            );
          } else {
            setSelected(null);
            setInstallers([]);
          }
        }}
        onChangeText={text => {
          setSearch(text);
          setSelected(null);
          if (text) {
            setInstallers(
              totalList.current.filter(item =>
                item.name.toLowerCase().includes(text.toLowerCase()),
              ),
            );
          } else {
            setInstallers([]);
          }
        }}></TextInput>
      <View
        className="mt-2 max-h-[500] flex-1"
        style={{
          display: open ? 'flex' : 'none',
        }}>
        <FlashList
          keyboardShouldPersistTaps="handled"
          data={installers}
          showsVerticalScrollIndicator={false}
          renderItem={renderItem}
          keyExtractor={item => item.instId}></FlashList>
      </View>
    </View>
  );
};

export default InstallerPicker;
